﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using LEEAAttendanceControl.Web;
using LEEAAttendanceControl.Web.Services;

using System.ServiceModel.DomainServices.Client;

namespace LEEAAttendanceControl.Views
{
    public partial class ExceptionEdit : ChildWindow
    {
        LEEAContext context = new LEEAContext();

        Exeption exception = new Exeption();

        public ExceptionEdit()
        {
            InitializeComponent();
        }

        public ExceptionEdit(string title)
        {
            Title = title;

            InitializeComponent();
        }

        public void LoadData(int id)
        {
            context.Load(context.GetExceptionByIdQuery(id), OnExceptionLoadCompleted, null);
        }

        private void OnExceptionLoadCompleted(LoadOperation load)
        {
            context.Load(context.GetCompaniesQuery()).Completed += (s, e) =>
                {
                    CompanyCombo.ItemsSource = context.Companies;

                    exception = (Exeption)load.Entities.FirstOrDefault();

                    if (exception == null)
                    {
                        exception = new Exeption();

                        exception.DPH = 8;

                        context.Exeptions.Add(exception);
                    }

                    DataContext = exception;
                };
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            context.SubmitChanges(OnChangesSubmitted, null);
        }

        private void OnChangesSubmitted(SubmitOperation so)
        {
            if (so.HasError)
            {
                so.MarkErrorAsHandled();
                MessageDisplay message = new MessageDisplay(ApplicationStrings.GeneralError
                    , ApplicationStrings.GeneralError, "Error");
                message.Show();
            }
            else
            {
                MessageDisplay message = new MessageDisplay(ApplicationStrings.GeneralSave
                    , ApplicationStrings.GeneralSave, "Save");

                message.Closed += (s, e) =>
                {
                    this.DialogResult = true;
                };

                message.Show();
            }
        }
    }
}

